package com.example.mywebrtc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class ClientActivity extends Activity {
    private final int MSG_INIT_SUCCESS = 0;
    private final int MSG_USER_JOINED = 1;
    private final int MSG_USER_LEAVE = 2;
    private final int MSG_USER_GET = 3;
    private final int MSG_USER_COMMING = 4;
    private final int MSG_USER_COMMING_CANCEL = 5;
    private final int MSG_USER_COMMING_ANSWERED = 6;
    private final int MSG_USER_ROOM_ANSWERED = 7;
    private ListView listView;
    private List<String> socketIds;
    private Adapter adapter;
    private AlertDialog mCommingDialog;
    private AlertDialog mCallDialog;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_INIT_SUCCESS) {
                Toast.makeText(ClientActivity.this, "连接服务器成功",Toast.LENGTH_SHORT).show();
            } else if (msg.what == MSG_USER_JOINED) {
                String id = (String) msg.obj;
                socketIds.add(id);
                adapter.notifyDataSetChanged();
                Toast.makeText(ClientActivity.this,  id + "上线",Toast.LENGTH_SHORT).show();
            } else if (msg.what == MSG_USER_LEAVE) {
                String id = (String) msg.obj;
                socketIds.remove(id);
                adapter.notifyDataSetChanged();
                Toast.makeText(ClientActivity.this,  id + "下线",Toast.LENGTH_SHORT).show();


            } else if (msg.what == MSG_USER_GET) {
                String id = (String) msg.obj;
                socketIds.add(id);
                adapter.notifyDataSetChanged();
            } else if (msg.what == MSG_USER_COMMING) {
                String id = (String) msg.obj;
                comming(id);
            } else if (msg.what == MSG_USER_COMMING_CANCEL) {
                if (mCommingDialog != null && mCommingDialog.isShowing()) {
                    mCommingDialog.dismiss();
                }
                if (mCallDialog != null && mCallDialog.isShowing()) {
                    mCallDialog.dismiss();
                }
            } else if (msg.what == MSG_USER_COMMING_ANSWERED) {
                if (mCallDialog != null && mCallDialog.isShowing()) {
                    mCallDialog.dismiss();
                }
                String id = (String) msg.obj;
                Intent intent = new Intent(ClientActivity.this, MainActivity.class);
                intent.putExtra("room","");
                intent.putExtra("id",id);
                ClientActivity.this.startActivity(intent);
            } else if (msg.what == MSG_USER_ROOM_ANSWERED) {
                String room = (String) msg.obj;
                Intent intent = new Intent(ClientActivity.this, MainActivity.class);
                intent.putExtra("room",room);
                intent.putExtra("id","");
                ClientActivity.this.startActivity(intent);
            }
        }
    };

    private void comming(String id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this,R.layout.call_dialog_receive,null);
        builder.setView(view);
        builder.setCancelable(false);
        Button button = view.findViewById(R.id.but_cancel);
        Button buttonOk = view.findViewById(R.id.but_ok);
        mCommingDialog = builder.create();
        mCommingDialog.show();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommingDialog.dismiss();
                SignalingClient.get().callCancel(id);
            }
        });

        buttonOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommingDialog.dismiss();
                SignalingClient.get().callOk(id);
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        listView = findViewById(R.id.lv_list);
        socketIds = new ArrayList<>();
        adapter = new Adapter();
        listView.setAdapter(adapter);
        SignalingClient.get().setClientInitCallback(new SignalingCallBack());

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                call(socketIds.get(position));
            }
        });
    }

    private void call(String s) {
        SignalingClient.get().call(s);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(this,R.layout.call_dialog_send,null);
        builder.setView(view);
        builder.setCancelable(false);
        Button button = view.findViewById(R.id.but_cancel);
        mCallDialog = builder.create();
        mCallDialog.show();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallDialog.dismiss();
                SignalingClient.get().callCancel(s);
            }
        });
    }

    class SignalingCallBack implements SignalingClient.ClientInitCallback{

        @Override
        public void initSocketSuccess() {
            mHandler.sendEmptyMessage(MSG_INIT_SUCCESS);
        }

        @Override
        public void userJoined(String socketId) {
            Message msg = mHandler.obtainMessage(MSG_USER_JOINED,socketId);
            mHandler.sendMessage(msg);
        }

        @Override
        public void userLeave(String socketId) {
            Message msg = mHandler.obtainMessage(MSG_USER_LEAVE,socketId);
            mHandler.sendMessage(msg);
        }

        @Override
        public void getUser(String id) {
            Message msg = mHandler.obtainMessage(MSG_USER_GET,id);
            mHandler.sendMessage(msg);
        }

        @Override
        public void comming(String id) {
            Message msg = mHandler.obtainMessage(MSG_USER_COMMING,id);
            mHandler.sendMessage(msg);
        }

        @Override
        public void commingCancel(String id) {
            Message msg = mHandler.obtainMessage(MSG_USER_COMMING_CANCEL,id);
            mHandler.sendMessage(msg);
        }

        @Override
        public void commingAnswered(String id) {
            Message msg = mHandler.obtainMessage(MSG_USER_COMMING_ANSWERED,id);
            mHandler.sendMessage(msg);
        }

        @Override
        public void callRoomCreate(String room) {
            Message msg = mHandler.obtainMessage(MSG_USER_ROOM_ANSWERED,room);
            mHandler.sendMessage(msg);
        }
    }

    class Adapter extends BaseAdapter{

        @Override
        public int getCount() {
            return socketIds.size();
        }

        @Override
        public Object getItem(int position) {
            return socketIds.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(ClientActivity.this,R.layout.listview_item,null);
            TextView tv = view.findViewById(R.id.tv_id);
            tv.setText(socketIds.get(position));
            return view;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SignalingClient.get().destroy();
    }
}
